/**
 * Created by TomSean on 2017/5/29.
 */
var AccessPermissionManager = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}

AccessPermissionManager.prototype = {
    init : function() {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent.find(".search-panel"));
        var functionArray = [
            {fName : 'search_btn', fs : this.findData},
            {fName : 'reset_btn', fs : this.resetInfo}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#search_enable'), parentModelKey:BASIS.DATA_STATUS.ROOT}, this);
        var sHeight = (this.$parent.find('.search-panel')[0].clientHeight);
        var allHeight = (this.$parent[0].clientHeight);
        this.$parent.find('#access_permission_data_list').height(allHeight-sHeight-2);

        this.initTable();
        this.findData();
    },
    // 重置按钮
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
    },
    // 初始化table （数据列表）
    initTable : function() {
        var _this = this;
        var columns = [
            {
                width:30,
                headerTemplate : '<input type="checkbox" gridId="access_permission_data_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="id" value="${id}">'
            },
            {
                title : '权限组编号',
                field : 'accessCode'
            },
            {
                title : '权限组名称',
                field : 'accessName'
            },
            {
                title : '状态',
                template : '#:Utils.getModelNameByParentKey(BASIS.DATA_STATUS.ROOT, isEnable)#'
            },
            {
                title : '创建时间',
                field : 'createTime'
            },
            {
                title : '创建人',
                field : 'createUserid'
            }
        ];
        _this.sysUtils.createGird(
            _this.$parent.find('#access_permission_data_list'),
            {
                selectable : 'single',
                autoSync : true,
                columnMenu : true,
                pageable : {input : true, numeric : false},
                columns : columns,
                change : function() {
                    var selected = $.map(this.select(), function(itm) {
                        return $(itm).find("input[type=checkbox]").val();
                    });
                    _this.selectRowId = selected[0];
                }
            });
    },

    // 查询方法
    findData : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var grid = _this.$parent.find('#access_permission_data_list').data('kendoGrid');
        var params = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
        var dataSource = _this.sysUtils.getDataSource({
            url : baseApiPath + 'access_permission/list',
            data : {'curdatetime':new Date().getTime(), 'jsonParam':JSON.stringify(params)},
            dataType : 'odata'
        });
        grid.setDataSource(dataSource);
    },

    // 打开编辑数据的弹出层（会先查询数据记录，充填到entity 变量中）
    openEditWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var id = _this.selectRowId;
        if (isEmpty(id)) {
            notification({title : '警告' , message : '请先选择需要编辑的数据'}, 'info');
            return;
        }
        _this.isEdit = true;
        JsonpAjax(baseApiPath + 'access_permission/get/'+id, undefined, 'json', function(res) {
            _this.entity = res;
            _this.openWindow('编辑权限组');
        }, true);
    },

    // 打开新建数据的弹出层
    openNewWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.isEdit = false;
        _this.openWindow('新建权限组');
    },

    // 打开弹出层
    openWindow : function(title) {
        this.editDiv = this.sysUtils.openWindow(this.editDiv, {
            title : title,
            height : '470px',
            width : '800px',
            resizable : false,
            content : 'views/parkLotCenter/parkingLotInfo/passTypeEdit.html'
        }, true);
    },

    deleteData : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var ids = '';
        _this.$parent.find('input[name="id"]:checked').each(function (inx, itm) {
            ids += $(itm).val() + ',';
        });
        if (ids == '') {
            notification({title : '警告', message : '请至少勾选一项要删除的数据'}, 'info');
            return;
        }
        ids = ids.substring(0, ids.length - 1);
        JsonpAjax(baseApiPath + 'access_permission/delete?ids='+ids, '', 'json', function (res){
            _this.findData();
        }, false);
    }
};

var AccessPermissionEdit = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
};
AccessPermissionEdit.prototype = {
    init : function() {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'save_info', fs : this.saveInfo },
            {fName : 'cancel', fs : function() { $('#' + permitType.editDiv).data('kendoWindow').close(); } }
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#type_status'), parentModelKey:BASIS.DATA_STATUS.ROOT}, this);
        this.loadTree();
        this.loadInfo();
    },

    // 若此时为编辑状态，则加载数据的信息
    loadInfo : function() {
        var entity = permitType.entity;
        if (!isEmpty(entity)) {
            this.sysUtils.setBindFieldValue(entity);
            this.codeStr = entity.accessChannelCode;
            permitType.entity = undefined;
            permitType.isEdit = false;
        }
    },

    // 保存
    saveInfo : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (validityForm(_this.$parent)) {
            var treeObj = $.fn.zTree.getZTreeObj("permit_tree");
            var nodes = treeObj.getCheckedNodes(true);
            var ids = '';
            for (var i = 0; i < nodes.length; i++) {
                if ( nodes[i].type.indexOf('chn_') != -1 ){
                    ids += nodes[i].code+',';
                }
            }
            if (!isEmpty(ids)) {
                ids = ids.substring(0, ids.length - 1);
            }
            var dataT = {permits : ids, permitType : JSON.stringify(_this.sysUtils.getBindDocJson())};
            JsonpAjax(baseApiPath + 'access_permission/save', JSON.stringify(dataT), 'json', function(res) {
                $('#' + permitType.editDiv).data('kendoWindow').close();
                permitType.findData();
            }, true);
        }
    },

    // 加载可通行通道的树节点
    loadTree : function () {
        var _this = this;
        var setting = {
            view: {
                showLine: true,
                selectedMulti: false,
                dblClickExpand: false,
                showIcon: false
            },
            data: {
                simpleData: {
                    enable:true,
                    idKey: "code",
                    pIdKey: "pid",
                    rootPId: ""
                }
            },
            async: {
                enable: true,
                type:"post",
                url: baseApiPath + "access_permission/channel/tree",
            },
            check : {
                enable: true,
                autoCheckTrigger: true,
                chkStyle: "checkbox",
                chkboxType: { "Y": "ps", "N": "ps" }
            },
            callback : {
                onAsyncSuccess : function() {
                    var treeObj = $.fn.zTree.getZTreeObj("permit_tree");
                    treeObj.expandAll(true);
                    var codes = !isEmpty(_this.codeStr) ? _this.codeStr.split(',') : '';
                    if ( codes.length > 0 ){
                        for (var i = 0; i < codes.length; i++) {
                            var node = treeObj.getNodeByParam('code', codes[i], null);
                            if (undefined != node) {
                                treeObj.checkNode(node, true, true);
                            }
                        }
                    }
                }
            }
        };
        var t = this.$parent.find("#permit_tree");
        t = $.fn.zTree.init(t, setting);
    }
};